<template>
  <view class="admin-wallpaper-page">
    <view class="page-header">
      <view class="header-left">
        <view class="back-btn" @click="navigateBack">
          <!-- <view class="icon icon-arrow-left" style="font-size: 20px;">‹</view> -->
          <!-- <text class="header-title">壁纸管理</text> -->
        </view>
      </view>
      <view class="header-right">
        <button class="add-btn" type="primary" size="mini" @click="navigateToUpload">
          上传壁纸
        </button>
      </view>
    </view>
    
    <!-- 搜索和筛选 -->
    <view class="search-filter">
      <view class="search-box">
        <view class="icon icon-search" style="font-size: 18px; color: #999;">🔍</view>
        <input 
          v-model="searchKeyword" 
          type="text" 
          placeholder="搜索壁纸名称或标签" 
          class="search-input"
          @confirm="searchWallpapers"
        />
      </view>
      <picker 
          :range="categoryOptions"
          mode="selector" 
        range-key="name"
        @change="onCategoryChange"
      >
        <view class="category-picker">
          <text>{{ selectedCategory ? categoryMap[selectedCategory].name : '全部分类' }}</text>
          <view class="icon icon-arrow-down" style="font-size: 16px; color: #999;">▼</view>
        </view>
      </picker>
    </view>
    
    <!-- 壁纸列表 -->
    <view class="wallpaper-grid" v-if="wallpapers.length > 0">
      <view 
        v-for="wallpaper in wallpapers" 
        :key="wallpaper._id" 
        class="wallpaper-item"
      >
        <view class="wallpaper-image-wrapper">
          <image :src="wallpaper.imageUrl" mode="aspectFill" class="wallpaper-image" @click="previewWallpaper(wallpaper)"></image>
          <view class="image-overlay">
            <view class="status-badge" :class="{ 'active': getWallpaperStatus(wallpaper) }">
              {{ getWallpaperStatus(wallpaper) ? '正常' : '下架' }}
            </view>
          </view>
        </view>
        <view class="wallpaper-info">
          <text class="wallpaper-name">{{ wallpaper.title }}</text>
          <text class="wallpaper-category">{{ getCategoryName(wallpaper.categoryId) }}</text>
          <view class="wallpaper-stats">
            <text class="stat-item">👍 {{ wallpaper.likes || 0 }}</text>
            <text class="stat-item">💾 {{ wallpaper.downloads || 0 }}</text>
            <text class="stat-item">⭐ {{ wallpaper.favorites || 0 }}</text>
            <text class="stat-item">👁 {{ wallpaper.views || 0 }}</text>
          </view>
        </view>
        <view class="action-buttons">
          <button size="mini" type="primary" @click="editWallpaper(wallpaper)">编辑</button>
          <button 
            size="mini" 
            type="warn" 
            @click="deleteWallpaper(wallpaper)"
          >
            删除
          </button>
          <button 
            size="mini" 
            :type="getWallpaperStatus(wallpaper) ? 'default' : 'primary'"
            @click="toggleWallpaperStatus(wallpaper)"
          >
            {{ getWallpaperStatus(wallpaper) ? '下架' : '上架' }}
          </button>
        </view>
      </view>
    </view>
    
    <!-- 加载更多 -->
    <view v-if="hasMore && wallpapers.length > 0" class="load-more" @click="loadMoreWallpapers">
      <text v-if="!isLoading">点击加载更多</text>
      <text v-else>加载中...</text>
    </view>
    
    <!-- 空状态 -->
    <view v-if="wallpapers.length === 0 && !isLoading" class="empty-state">
      <view class="icon icon-image" style="font-size: 64px; color: #ccc;">🖼️</view>
      <text class="empty-text">暂无壁纸</text>
    </view>
    
    <!-- 加载状态 -->
    <view v-if="isLoading && wallpapers.length === 0" class="loading-state">
      <view class="loading-spinner"></view>
      <text class="loading-text">加载中...</text>
    </view>
    
    <!-- 底部提示 -->
    <view v-if="wallpapers.length > 0 && !hasMore" class="bottom-tip">
      <text class="bottom-tip-text">已加载全部壁纸</text>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive } from 'vue';
import { onLoad, onShow} from "@dcloudio/uni-app"

// 状态管理
const searchKeyword = ref('');
const selectedCategory = ref('');
const wallpapers = ref([]);
const categories = ref([]);
const categoryOptions = ref([{ id: '', name: '全部分类' }]);
const categoryMap = ref({});
const pageSize = 20;
const currentPage = ref(1);
const hasMore = ref(true);
const isLoading = ref(false);

// 生命周期
onLoad(() => {
  loadWallpapers();
  loadCategories();
});

onShow(() => {
  // 每次显示页面时重新加载数据
  resetAndLoadWallpapers();
  loadCategories();
});

// 管理员权限校验已移除

// 重置并加载壁纸
const resetAndLoadWallpapers = () => {
  currentPage.value = 1;
  hasMore.value = true;
  loadWallpapers(false);
};

// 加载分类数据
const loadCategories = async () => {
  try {
    const res = await uniCloud.callFunction({
      name: 'admingetCategories'
    });
    
    if (res && res.result && res.result.code === 0) {
      categories.value = res.result.data;
      buildCategoryOptionsAndMap();
    } else {
      // 使用模拟数据
      mockCategories();
    }
  } catch (error) {
    console.error('加载分类失败:', error);
    // 使用模拟数据
    mockCategories();
  }
};

// 构建分类选项和映射
const buildCategoryOptionsAndMap = () => {
  const options = [{ id: '', name: '全部分类' }];
  const map = {};
  
  categories.value.forEach(cat => {
    options.push({ id: cat._id, name: cat.name });
    map[cat._id] = cat;
  });
  
  categoryOptions.value = options;
  categoryMap.value = map;
};



// 加载壁纸数据
const loadWallpapers = async (isLoadMore = false) => {
  if (isLoading.value) return;
  
  isLoading.value = true;
  
  try {
    const page = isLoadMore ? currentPage.value + 1 : 1;
    
    const result = await uniCloud.callFunction({
      name: 'admingetWallpapers',
      data: {
        keyword: searchKeyword.value.trim(),
        categoryId: selectedCategory.value || undefined,
        page,
        pageSize
      }
    });
    
    console.log('获取列表',result);
    if (result && result.result && result.result.code === 0) {
      const newWallpapers = result.result.data || [];
      
      if (isLoadMore) {
        wallpapers.value = [...wallpapers.value, ...newWallpapers];
      } else {
        wallpapers.value = newWallpapers;
      }
      
      hasMore.value = newWallpapers.length === pageSize;
      currentPage.value = page;
    } else {
      // 处理错误情况
      console.error('获取壁纸列表失败:', result);
      uni.showToast({
        title: result?.result?.message || '获取数据失败',
        icon: 'none',
        duration: 2000
      });
    }
  } catch (error) {
    console.error('获取壁纸列表异常:', error);
    uni.showToast({
      title: error?.message || '获取数据异常',
      icon: 'none',
      duration: 2000
    });
  } finally {
    isLoading.value = false;
  }
};






// 搜索壁纸
const searchWallpapers = () => {
  resetAndLoadWallpapers();
};

// 分类改变
const onCategoryChange = (e) => {
  const index = e.detail.value;
  selectedCategory.value = categoryOptions.value[index]?.id || '';
  resetAndLoadWallpapers();
};

// 加载更多
const loadMoreWallpapers = () => {
  if (hasMore.value && !isLoading.value) {
    loadWallpapers(true);
  }
};

// 获取分类名称
const getCategoryName = (categoryId) => {
  if (!categoryId) return '未分类';
  return categoryMap.value[categoryId]?.name || '未知分类';
};

// 获取壁纸状态
const getWallpaperStatus = (wallpaper) => {
  if (wallpaper.status === 'approved' || wallpaper.status === 1 || wallpaper.status === true) {
    return true;
  }
  return false;
};

// 获取新状态值
const getNewStatus = (currentActive) => {
  return currentActive ? 'disabled' : 'approved';
};

// 预览壁纸
const previewWallpaper = (wallpaper) => {
  uni.previewImage({
    urls: [wallpaper.imageUrl],
    current: 0
  });
};

// 编辑壁纸
const editWallpaper = (wallpaper) => {
  uni.navigateTo({
    url: `/pages/admin/edit-wallpaper?id=${wallpaper._id}`
  });
};

// 删除壁纸
const deleteWallpaper = (wallpaper) => {
  uni.showModal({
    title: '确认删除',
    content: `确定要删除壁纸「${wallpaper.title}」吗？此操作不可恢复。`,
    success: async (res) => {
      if (res.confirm) {
        // 显示加载提示
        uni.showLoading({
          title: '删除中...'
        });
        
        try {
          // 直接调用云函数，不使用模拟响应
          const result = await uniCloud.callFunction({
            name: 'admindeleteWallpaper',
            data: { id: wallpaper._id }
          });
          
          uni.hideLoading();
          
          if (result && result.result && result.result.code === 0) {
            // 从列表中移除该壁纸
            const index = wallpapers.value.findIndex(item => item._id === wallpaper._id);
            if (index > -1) {
              wallpapers.value.splice(index, 1);
            }
            
            uni.showToast({ 
              title: '删除成功', 
              icon: 'success',
              duration: 2000
            });
          } else {
            const errorMsg = result?.result?.message || '删除失败';
            uni.showToast({ 
              title: errorMsg, 
              icon: 'none',
              duration: 2000
            });
            console.error('删除壁纸失败:', errorMsg);
          }
        } catch (error) {
          uni.hideLoading();
          console.error('删除壁纸异常:', error);
          
          // 显示实际的错误信息
          const errorMessage = error?.message || '删除失败，请稍后重试';
          uni.showToast({ 
            title: errorMessage,
            icon: 'none',
            duration: 2000
          });
        }
      }
    }
  });
};

// 切换壁纸状态
const toggleWallpaperStatus = async (wallpaper) => {
  const currentActive = getWallpaperStatus(wallpaper);
  const newStatus = getNewStatus(currentActive);
  const statusText = newStatus === 'approved' ? '上架' : '下架';
  
  // 提前获取索引，避免作用域问题
  const index = wallpapers.value.findIndex(item => item._id === wallpaper._id);
  
  // 显示加载提示
  uni.showLoading({
    title: '处理中...'
  });
  
  try {
    // 先在本地临时更新状态，提供即时反馈
    if (index > -1) {
      wallpapers.value[index].status = newStatus;
    }
    
    // 直接调用云函数，不使用模拟响应
    const result = await uniCloud.callFunction({
      name: 'adminupdateWallpaperStatus',
      data: {
        id: wallpaper._id,
        status: newStatus
      }
    });
    
    uni.hideLoading();
    console.log('状态修改结果:', result);
    
    if (result && result.result && result.result.code === 0) {
      uni.showToast({ 
        title: `${statusText}成功`, 
        icon: 'success',
        duration: 2000
      });
    } else {
      // 操作失败，恢复原状态
      if (index > -1) {
        wallpapers.value[index].status = currentActive ? 'approved' : 'disabled';
      }
      
      const errorMsg = result?.result?.message || `${statusText}失败`;
      uni.showToast({ 
        title: errorMsg, 
        icon: 'none',
        duration: 2000
      });
      console.error(`${statusText}壁纸失败:`, errorMsg);
    }
  } catch (error) {
    uni.hideLoading();
    console.error(`${statusText}壁纸异常:`, error);
    
    // 异常情况，恢复原状态
    if (index > -1) {
      wallpapers.value[index].status = currentActive ? 'approved' : 'disabled';
    }
    
    // 显示实际的错误信息
    const errorMessage = error?.message || `${statusText}操作失败，请稍后重试`;
    uni.showToast({ 
      title: errorMessage,
      icon: 'none',
      duration: 2000
    });
  }
};

// 导航返回
const navigateBack = () => {
  uni.navigateBack();
};

// 跳转到上传页面
const navigateToUpload = () => {
  uni.navigateTo({
    url: '/pages/admin/upload-wallpaper'
  });
};
</script>

<style scoped lang="less">
.icon {
  display: inline-flex;
  align-items: center;
  justify-content: center;
}
.admin-wallpaper-page {
  background-color: #f5f5f5;
  min-height: 100vh;
  padding-bottom: 40rpx;
  
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px;
    background-color: #fff;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
    
    .header-left {
      display: flex;
      align-items: center;
      
      .back-btn {
        display: flex;
        align-items: center;
        
        .header-title {
          font-size: 18px;
          font-weight: 600;
          color: #333;
          margin-left: 4px;
        }
      }
    }
    
    .header-right {
      .add-btn {
        font-size: 14px;
        background-color: #007aff;
      }
    }
  }
  
  .search-filter {
    padding: 16px;
    background-color: #fff;
    margin-bottom: 12px;
    
    .search-box {
      display: flex;
      align-items: center;
      background-color: #f5f5f5;
      border-radius: 20px;
      padding: 0 12px;
      margin-bottom: 12px;
      
      .search-input {
        flex: 1;
        height: 36px;
        font-size: 14px;
        padding-left: 8px;
      }
    }
    
    .category-picker {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 10px 12px;
      background-color: #f5f5f5;
      border-radius: 8px;
      font-size: 14px;
      color: #333;
    }
  }
  
  .wallpaper-grid {
    padding: 0 16px;
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 12px;
  }
  
  .wallpaper-item {
    background-color: #fff;
    border-radius: 12px;
    overflow: hidden;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
    
    .wallpaper-image-wrapper {
      position: relative;
      width: 100%;
      height: 150px;
      
      .wallpaper-image {
        width: 100%;
        height: 100%;
      }
      
      .image-overlay {
        position: absolute;
        top: 8px;
        left: 8px;
        
        .status-badge {
          padding: 2px 8px;
          border-radius: 4px;
          font-size: 12px;
          background-color: rgba(0, 0, 0, 0.5);
          color: #fff;
          
          &.active {
            background-color: rgba(0, 128, 0, 0.7);
          }
        }
      }
    }
    
    .wallpaper-info {
      padding: 10px;
      
      .wallpaper-name {
        display: block;
        font-size: 14px;
        font-weight: 500;
        color: #333;
        margin-bottom: 4px;
        display: -webkit-box;
        -webkit-line-clamp: 1;
        -webkit-box-orient: vertical;
        overflow: hidden;
      }
      
      .wallpaper-category {
        display: block;
        font-size: 12px;
        color: #666;
        margin-bottom: 6px;
      }
      
      .wallpaper-stats {
        display: flex;
        flex-wrap: wrap;
        gap: 8px;
        
        .stat-item {
          font-size: 11px;
          color: #999;
        }
      }
    }
    
    .action-buttons {
      padding: 0 10px 10px;
      display: flex;
      gap: 8px;
      
      button {
        flex: 1;
        font-size: 11px;
        height: 26px;
        line-height: 26px;
      }
    }
  }
  
  .load-more {
    text-align: center;
    padding: 16px;
    font-size: 14px;
    color: #007aff;
  }
  
  .empty-state {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 64px 0;
    
    .empty-text {
      font-size: 14px;
      color: #999;
      margin-top: 16px;
    }
  }
  
  .loading-state {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 64px 0;
    
    .loading-spinner {
      width: 30px;
      height: 30px;
      border: 3px solid #f3f3f3;
      border-top: 3px solid #007aff;
      border-radius: 50%;
      animation: spin 1s linear infinite;
    }
    
    .loading-text {
      font-size: 14px;
      color: #666;
      margin-top: 16px;
    }
  }
  
  .bottom-tip {
    text-align: center;
    padding: 20px 0;
    
    .bottom-tip-text {
      font-size: 12px;
      color: #999;
    }
  }
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}
</style>